package com.yxw.live_vod_boot.service.impl;


import com.yxw.live_vod_boot.mapper.CreateTableMapper;
import com.yxw.live_vod_boot.service.CreateTableService;
import com.yxw.live_vod_boot.utils.RedisManager;
import com.yxw.yxnet_cd_center.common.enums.CreateTableEnum;
import com.yxw.yxnet_cd_center.common.utils.BaseDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;

/**
 * 创建表service
 * @author liuxin
 * @date 2023.09.25
 */
@Service
public class CreateTableServiceImpl implements CreateTableService {

    @Autowired
    private CreateTableMapper createTableMapper;

    @Autowired
    private RedisManager redisManager;

    /**
     * 创建表
     * @param tableEnum
     */
    @Override
    public String createTable(CreateTableEnum tableEnum) {
        //查询创建表是否已存在
        String tableName=tableEnum.getTableName()+"_"+BaseDateTime.getStrDateByFormat(new Date(),tableEnum.getFormat());
        //查询redis是否存在该表
        Object o = redisManager.get(tableName);
        if(null==o){
            Boolean isExists =isTableExists(tableName);
            if(!isExists){
                createTableMapper.createTableByName(tableEnum.getTableName(),tableName,tableEnum.getPrikey(),tableEnum.getRemark());
                //删除前一个月月表
                // 获取当前时间
                Date currentDate = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentDate);
                calendar.add(Calendar.MONTH, -1);
                Date lastMonthDate = calendar.getTime();
                String lastTableName=tableEnum.getTableName()+"_"+BaseDateTime.getStrDateByFormat(lastMonthDate,tableEnum.getFormat());
                redisManager.del(lastTableName);
            }
            redisManager.set(tableName,true);
        }
        return tableName;
    }

    /**
     * 表是否存在
     * @param tableName
     */
    private Boolean isTableExists(String tableName){
        Integer count=createTableMapper.getTableByName(tableName);
        if(count<1){
            return false;
        }
        return true;
    }
}
